import dictService, { type PageListReq } from "@/api/services/system/dictService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import { formatDate } from "@fullcalendar/core/index.js";
import { Button, Card, Drawer, Flex, Form, Input, Select, Space, Tag, message } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import { t } from "i18next";
import { useEffect, useMemo, useState } from "react";
import type { Dict } from "#/entity";
import { BasicStatus } from "#/enum";
import DictItemPage from "./DictItem";
import { useDictionaryStore } from "@/store/useDictionaryStore";

export default function DictPage() {
	const [loading, setLoading] = useState(false);
	const [queryParams, setQueryParams] = useState<PageListReq>({
		dictCode: "",
		dictName: "",
		page: 1,
		pageSize: 10,
	});
	const [editingDict, setEditingDict] = useState<Dict | null>(null);
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<Dict[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
	const [form] = Form.useForm();
	const [isView, setIsView] = useState(true);
	const [drawerVisible, setDrawerVisible] = useState(false);

	const [dictItemOpen, setDictItemOpen] = useState(false);

	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");

	// 定义表格列
	const columns: ColumnsType<Dict> = [
		{
			title: "编码",
			dataIndex: "dictCode",
			key: "dictCode",
		},
		{
			title: "名称",
			dataIndex: "dictName",
			key: "dictName",
		},
		{
			title: "状态",
			dataIndex: "status",
			key: "status",
			align: "center",
			render: (status) => (
				<Tag color={status === BasicStatus.DISABLE ? "error" : "success"}>
					{status === BasicStatus.DISABLE ? "失效" : "有效"}
				</Tag>
			),
		},
		{ title: "描述", dataIndex: "description", key: "description" },
		{
			title: "创建时间",
			key: "createTime",
			dataIndex: "createTime",
			align: "center",
			width: 120,
			render: (time) => formatDate(time, { locale: "zh-cn" }),
		},
		{
			title: "操作",
			key: "operation",
			align: "center",
			width: 230,
			render: (_, record) => (
				<Flex gap="small" wrap>
					<Button type="link" onClick={() => handleView(record)}>
						{t("common.view")}
					</Button>
					<Button type="link" onClick={() => handleEdit(record)}>
						{t("common.edit")}
					</Button>
					<Button type="link" onClick={() => addItems(record)}>
						字典项
					</Button>
				</Flex>
			),
		},
	];

	// 状态管理
	const [selectedValues, setSelectedValues] = useState<string[]>(() =>
		columns.filter((col) => col.key !== "operation").map((col) => String(col.key!)),
	);
	// 处理过滤后的列配置
	const filteredColumns = useMemo(() => {
		return [
			// 显示选中的列
			...columns.filter(
				(col) => selectedValues.includes(String(col.key)) || col.key === "operation", // 始终包含操作列
			),
		].sort((a, b) => {
			// 保持原始顺序
			const originalIndex = columns.findIndex((c) => c.key === a.key);
			const targetIndex = columns.findIndex((c) => c.key === b.key);
			return originalIndex - targetIndex;
		});
	}, [selectedValues]);

	const fetchList = async () => {
		try {
			setLoading(true);
			const res = await dictService.pageList(queryParams);
			setList(res.records);
			setTotal(res.total);
		} catch (error) {
			console.error("获取字典列表失败:", error);
		} finally {
			setLoading(false);
		}
	};

	useEffect(() => {
		fetchList();
	}, [queryParams]);

	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	const handleAdd = () => {
		form.resetFields();
		setDrawerVisible(true);
		setIsView(false);
	};

	//删除方法
	const handleDelete = async () => {
		try {
			setLoading(true);
			await dictService.deleteDict(selectedRowKeys);
			message.success("删除字典成功");
			setSelectedRowKeys([]); // 清空选中项
			fetchList(); // 重新加载列表
		} catch (error) {
			message.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	//删除缓存
	const refreshCache = async () => {
		try {
			setLoading(true);
			//服务器缓存
			await dictService.refreshCache();
			//浏览器缓存
			useDictionaryStore.getState().clearDictionary();
			message.success("刷新成功");
			setSelectedRowKeys([]); // 清空选中项
		} catch (error) {
			message.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	}

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		setEditingDict(null);
		form.resetFields();
	};

	const handleView = (record: Dict) => {
		setEditingDict(record);
		form.setFieldsValue(record);
		setIsView(true);
		setDrawerVisible(true);
	};

	const handleEdit = (record: Dict) => {
		setEditingDict(record);
		form.setFieldsValue(record);
		setDrawerVisible(true);
		setIsView(false);
	};

	const addItems = (recode: Dict) => {
		setEditingDict(recode);
		setDictItemOpen(true);
	};

	const handleSubmit = async (values) => {
		try {
			setLoading(true);
			if (editingDict) {
				await dictService.update({ ...values, id: editingDict.id });
				message.success("更新成功");
			} else {
				await dictService.add(values);
				message.success("创建成功");
			}
			setDrawerVisible(false);
			setEditingDict(null);
			form.resetFields();
			fetchList();
		} catch (error) {
			message.error(`${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	return (
		<>
			{/* 查询条件 */}
			<Card className="mb-4">
				<Form
					layout="inline"
					onFinish={(values) => {
						console.log("查询条件:", values);
						// 处理查询条件
						setQueryParams((prev) => ({
							...prev,
							...values,
							page: 1, // 查询时重置到第一页
						}));
					}}
				>
					<Form.Item name="dictCode" label="编码">
						<Input placeholder="请输入姓名" allowClear />
					</Form.Item>
					<Form.Item name="dictName" label="名称">
						<Input placeholder="请输入姓名" allowClear />
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button
							className="ml-2"
							onClick={() => {
								// 重置查询条件
								setQueryParams({ page: 1, pageSize: 10 });
							}}
						>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			<Card>
				<div className="flex justify-between mb-4">
					{/* 操作按钮 */}
					<div className="flex gap-2">
						<Button type="primary" onClick={handleAdd}>
							新增
						</Button>
						<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
							删除
						</Button>
						<Button onClick={refreshCache}>
							刷新缓存
						</Button>
					</div>
					<TableToolbar
						onRefresh={() => setQueryParams((prev) => ({ ...prev }))}
						onSizeChange={setTableSize}
						columns={columns}
						selectedValues={selectedValues}
						onColumnChange={setSelectedValues}
					/>
				</div>
				<Table
					rowKey="id"
					size={tableSize}
					scroll={{ x: "max-content" }}
					loading={loading}
					pagination={{
						total,
						current: queryParams.page,
						pageSize: queryParams.pageSize,
						onChange: handlePageChange,
					}}
					columns={columns}
					dataSource={list}
					rowSelection={{
						type: "checkbox",
						selectedRowKeys: selectedRowKeys,
						onChange: (selectedKeys) => {
							setSelectedRowKeys(selectedKeys as string[]);
						},
					}}
				/>
			</Card>
			{/* 字典编辑页面 */}
			<Drawer
				title={editingDict ? "编辑字典" : "新增字典"}
				width={480}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
						{!isView && (
							<Button type="primary" onClick={() => form.submit()}>
								确定
							</Button>
						)}
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
					<Form.Item name="dictCode" label="字典编码" rules={[{ required: true, message: "请输入字典编码" }]}>
						<Input placeholder="请输入字典编码" disabled={editingDict !== null} />
					</Form.Item>
					<Form.Item name="dictName" label="字典名称" rules={[{ required: true, message: "请输入字典名称" }]}>
						<Input placeholder="请输入字典名称" />
					</Form.Item>
					<Form.Item name="description" label="描述">
						<Input placeholder="请输入描述" />
					</Form.Item>

					<Form.Item name="status" label="状态" initialValue={BasicStatus.ENABLE}>
						<Select
							options={[
								{ label: "启用", value: BasicStatus.ENABLE },
								{ label: "禁用", value: BasicStatus.DISABLE },
							]}
						/>
					</Form.Item>
				</Form>
			</Drawer>
			<DictItemPage
				open={dictItemOpen}
				dict={editingDict}
				onClose={() => {
					setEditingDict(null);
					setDictItemOpen(false);
				}}
			/>
		</>
	);
}
